package cn.com.surker.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * cookies 操作工具
 *
 */
public class CookiesUtil {


	/**
	 * 根据key获取cookies值
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getCookies(HttpServletRequest request, String key) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie tmpCookie : cookies) {
				if (key.equals(tmpCookie.getName())) {
					return tmpCookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 设置cookies值
	 * @param key
	 * @param value
	 * @param response
	 */
	public static void setCookies(String key, String value ,HttpServletResponse response){
		Cookie tokenCookie = new Cookie(key, value);
		tokenCookie.setPath("/");
		tokenCookie.setMaxAge(Constant.COOKIE_EXPIRED);
		/**设置cookie**/
		response.addCookie(tokenCookie);
	}

	/**
	 * 删除cookies值
	 * @param key
	 * @param response
	 */
	public static void removeCookies(String key, HttpServletResponse response){
		Cookie tokenCookie = new Cookie(key, "");
		tokenCookie.setMaxAge(0);
		tokenCookie.setPath("/");
		response.addCookie(tokenCookie);
	}
	
}
